<template>
  <div>
    <div class="container">
      <el-card class="box-card" v-loading="loading">
        <h1 class="title">访问验证</h1>
        <h2>{{ question }}</h2>
        <el-input v-model="input" placeholder="请输入内容"></el-input>
        <el-button
          class="submit"
          type="success"
          @click="changeQ"
          icon="el-icon-refresh"
          >换一个问题</el-button
        >
        <el-button class="submit" type="primary" @click="submit"
          >提交验证</el-button
        >
      </el-card>
    </div>
  </div>
</template>
<script>
import { setSessionKey } from "../utils/cookie";
import { login } from "../api/login";
import { getQuestion, checkAnswer } from "../utils/question";
export default {
  name: "Login",
  data() {
    return {
      input: "",
      qId: 0,
      question: "",
      loading: false,
    };
  },
  methods: {
    submit() {
      if (this.input) {
        const check = checkAnswer(this.qId, this.input);
        if (check) {
          const timestamp = Date.parse(new Date());
          setSessionKey(timestamp);
          login().then((v) => {
            console.log(v);
            this.$message({
              message: "验证成功",
              type: "success",
            });

            setTimeout(() => {
              this.$router.push("/");
            }, 1000);
          });
        } else {
          this.$message.error("验证失败，请输入正确答案");
        }
      }
    },
    setQuestion() {
      const newQ = getQuestion();
      const len = newQ.length;
      const id = Math.round(Math.random() * (len - 1));
      this.qId = id;
      this.question = newQ[id];
    },
    changeQ() {
      (this.loading = true),
        setTimeout(() => {
          this.setQuestion();
          this.loading = false;
        }, 1000);
    },
  },
  created() {
    this.setQuestion();
  },
};
</script>
<style scoped>
.container {
  width: 50%;
  margin: 0 auto;
  margin-top: 200px;
}
.submit {
  margin-top: 20px;
  margin-right: 30px;
}
.box-card {
  padding: 10px 20px 40px 20px;
}
.title {
  color: #409eff;
  margin-top: 10px;
  margin-bottom: 50px;
}
</style>
